package br.com.beautycenter.view;
    
import br.com.beautycenter.DAO.PersisteDigital;
import br.com.beautycenter.bean.Digital;
import com.digitalpersona.onetouch.DPFPDataPurpose;
import com.digitalpersona.onetouch.DPFPFeatureSet;
import com.digitalpersona.onetouch.DPFPFingerIndex;
import com.digitalpersona.onetouch.DPFPGlobal;
import com.digitalpersona.onetouch.DPFPSample;
import com.digitalpersona.onetouch.DPFPTemplate;
import com.digitalpersona.onetouch.capture.DPFPCapture;
import com.digitalpersona.onetouch.capture.event.DPFPDataAdapter;
import com.digitalpersona.onetouch.capture.event.DPFPDataEvent;
import com.digitalpersona.onetouch.capture.event.DPFPErrorAdapter;
import com.digitalpersona.onetouch.capture.event.DPFPErrorEvent;
import com.digitalpersona.onetouch.capture.event.DPFPReaderStatusAdapter;
import com.digitalpersona.onetouch.capture.event.DPFPReaderStatusEvent;
import com.digitalpersona.onetouch.processing.DPFPFeatureExtraction;
import com.digitalpersona.onetouch.processing.DPFPImageQualityException;
import com.digitalpersona.onetouch.verification.DPFPVerification;
import com.digitalpersona.onetouch.verification.DPFPVerificationResult;
import java.net.URL;
import java.util.EnumMap;
import javax.swing.ImageIcon;
import javax.swing.JFrame;

public class PesquisarDigital extends javax.swing.JDialog {

    //objeto que realiza a captura da digital
    private DPFPCapture capturar = DPFPGlobal.getCaptureFactory().createCapture();
    private EnumMap<DPFPFingerIndex, DPFPTemplate> templates;
    DPFPTemplate template;
    
    //responsável por criar a digital que foi capturada
    private DPFPVerification verificator = DPFPGlobal.getVerificationFactory().createVerification();
    
    PersisteDigital persisteDigital = new PersisteDigital();
    private final URL STATUS_OK = getClass().getResource("/br/com/beautycenter/img/digital_status_ok.png");
    private final URL STATUS_ERRO = getClass().getResource("/br/com/beautycenter/img/digital_status_erro.png");
    private final URL STATUS_PESQUISA = getClass().getResource("/br/com/beautycenter/img/digital_pesquisar.png");
    private final URL STATUS_BUSCA_ERRO = getClass().getResource("/br/com/beautycenter/img/digital_erro_busca.png");
    
    private final ImageIcon ICON_STATUS_OK = new ImageIcon(STATUS_OK),
                      ICON_STATUS_ERRO = new ImageIcon(STATUS_ERRO), 
                      ICON_STATUS_PESQUISA = new ImageIcon(STATUS_PESQUISA), 
                      ICON_BUSCA_ERRO = new ImageIcon(STATUS_BUSCA_ERRO);

    public void pesquisarDigital(DPFPFeatureSet extractor){
        DPFPVerificationResult resultado; //verifica se ta ok
        
        for(Digital item: persisteDigital.retornarDigitais()){
            //cria o template a partir das digitais que estão no banco
            template = DPFPGlobal.getTemplateFactory().createTemplate(item.getDigital());
            
            //verifica se é igual a digital capturada
            resultado = verificator.verify(extractor, template);
            
            //se for, pega os dados do cliente
            if(resultado.isVerified()){
                inserirIcone(ICON_STATUS_OK);
                inserirMensagem("Cliente: " + item.getCliente().getNome());
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
                
                DadosCliente.cliente = item.getCliente();
                DadosCliente dadosCliente = new DadosCliente((JFrame)this.getParent(), false);
                dadosCliente.setLocationRelativeTo(null);
                dadosCliente.setVisible(true);
                dispose();
            }
        }
        
        //se chegar aqui é porque não localizou
        inserirIcone(ICON_BUSCA_ERRO);
        inserirMensagem("Digital não encontrada no banco de dados. "
                + "Tente novamente ou faça o cadastro desse do novo cliente.");
    }

    @Override
    public void dispose() {
        super.dispose(); //To change body of generated methods, choose Tools | Templates.
        capturar.stopCapture();
    }
    
    public void inserirMensagem(String mensagem){
        jLStatus.setText(mensagem); //imprime a mensagem mais um quebra de linha
    }
    
    public void inserirIcone(ImageIcon icon){
        jLIcon.setIcon(icon);
    }
    
    //listener para detectar o que está ocorrendo com o aparelho de captura de digital
    public void inicializar(){
        
        /** Status **/
        capturar.addReaderStatusListener(new DPFPReaderStatusAdapter(){
            //verifica se o aparelho está desligado
            @Override
            public void readerDisconnected(DPFPReaderStatusEvent dpfprs) {
                inserirIcone(ICON_STATUS_ERRO);
                inserirMensagem("O aparelho está desligado ou desconectado. Verifique-o!");
            }

            //verifica se o aparelho está conetado
            @Override
            public void readerConnected(DPFPReaderStatusEvent dpfprs) {
                inserirIcone(ICON_STATUS_OK);
                inserirMensagem("O aparelho está pronto para fazer a busca!");
            }
        });
        
        /** Captura da digital **/
        capturar.addDataListener(new DPFPDataAdapter(){

            //determina que o captura da digital está completa
            @Override
            public void dataAcquired(DPFPDataEvent e) {
                inserirIcone(ICON_STATUS_PESQUISA);
                inserirMensagem("Digital capturada com sucesso. Iniciando a busca no banco de dados...");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
                processamentoDigital(e.getSample());
            }
        });

        /** Status da captura da digital **/
        capturar.addErrorListener(new DPFPErrorAdapter(){
            //verifica se ocorreu algum erro durante a captura da digital
            @Override
            public void errorOccured(DPFPErrorEvent dpfpee) {
                inserirIcone(ICON_STATUS_ERRO);
                inserirMensagem("Ocorreu um erro na captura da digital, tente novamente.");
            }
        });
    }

    /**
     * Extrai as caracteristicas da digital para ser passado para o enroller
     * @param sample
     * @param purpose
     * @return 
     */
    protected DPFPFeatureSet extractFeatures(DPFPSample sample, DPFPDataPurpose purpose){
        DPFPFeatureExtraction extractor = DPFPGlobal.getFeatureExtractionFactory().createFeatureExtraction();
        try {
            return extractor.createFeatureSet(sample, purpose);
        } catch (DPFPImageQualityException e) {
            return null;
        }
    }
    
    public void processamentoDigital(DPFPSample capturada){
        DPFPFeatureSet caracteristicas = extractFeatures(capturada, DPFPDataPurpose.DATA_PURPOSE_VERIFICATION);
        
        if(caracteristicas != null){
            pesquisarDigital(caracteristicas);
        }
    }

    public PesquisarDigital(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        inicializar();
        capturar.startCapture();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPStatus = new javax.swing.JPanel();
        jLIcon = new javax.swing.JLabel();
        jPanelBotoes = new javax.swing.JPanel();
        btnFechar = new javax.swing.JButton();
        jLStatus = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Pesquisa pela Digital");

        jPStatus.setPreferredSize(new java.awt.Dimension(150, 150));

        jLIcon.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        javax.swing.GroupLayout jPStatusLayout = new javax.swing.GroupLayout(jPStatus);
        jPStatus.setLayout(jPStatusLayout);
        jPStatusLayout.setHorizontalGroup(
            jPStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 191, Short.MAX_VALUE)
            .addGroup(jPStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLIcon, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE))
        );
        jPStatusLayout.setVerticalGroup(
            jPStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 190, Short.MAX_VALUE)
            .addGroup(jPStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLIcon, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE))
        );

        jPanelBotoes.setBackground(new java.awt.Color(255, 255, 255));
        jPanelBotoes.setPreferredSize(new java.awt.Dimension(800, 45));

        btnFechar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/beautycenter/img/Sair.png"))); // NOI18N
        btnFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFecharActionPerformed(evt);
            }
        });
        jPanelBotoes.add(btnFechar);

        jLStatus.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLStatus.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLStatus.setText("jLabel1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
            .addComponent(jLStatus, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(222, 222, 222)
                .addComponent(jPStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(222, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanelBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFecharActionPerformed
        dispose();
    }//GEN-LAST:event_btnFecharActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnFechar;
    private javax.swing.JLabel jLIcon;
    private javax.swing.JLabel jLStatus;
    private javax.swing.JPanel jPStatus;
    private javax.swing.JPanel jPanelBotoes;
    // End of variables declaration//GEN-END:variables
}